﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZXing;
using ZXing.QrCode;
using iTextSharp;
using iTextSharp.text.pdf;
using System.Threading;

namespace QrCodeTool
{


    public partial class Main : Form
    {


        [System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数
        public static extern bool RegisterHotKey(
        IntPtr hWnd, // handle to window
        int id, // hot key identifier
        uint fsModifiers, // key-modifier options
        Keys vk // virtual-key code
        );

        [System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数
        public static extern bool UnregisterHotKey(
         IntPtr hWnd, // handle to window
         int id // hot key identifier
        );


        public Main()
        {
            InitializeComponent();
        }

        #region 模拟查询工具代码

        #region 截图模块

        //委托事件
        public delegate void copyToFatherTextBox(Rectangle r);

        private void bt_imagecut_Click(object sender, EventArgs e)
        {
            ScreenForm screen = new ScreenForm();
            screen.copytoFather += new copyToFatherTextBox(copytoTextBox);
            //设置置顶 调试时
            screen.TopMost = true;
            screen.ShowDialog();
        }

        /*截图后续操作*/
        public void copytoTextBox(Rectangle rec)
        {
            Rectangle rec2 = rec; //改造一下，去掉红色边框
            if (rec.Width > 2 && rec.Height > 2)
                rec2 = new Rectangle(rec.X + 1, rec.Y + 1, rec.Width - 2, rec.Height - 2);
            Rectangle r = Screen.PrimaryScreen.Bounds;
            Bitmap img = new Bitmap(rec2.Width, rec2.Height);
            Graphics g = Graphics.FromImage(img);
            g.CopyFromScreen(rec2.Location, new Point(0, 0), rec2.Size);
            //Clipboard.SetDataObject(img, false);
            //richTextBox1.Paste();

            //img.Save("D:\\" + DateTime.Now.ToShortTimeString() + ".jpg");

            //图片放大一倍提高识别率
            //Bitmap img2 = new Bitmap(img, new Size(img.Size.Width * 2, img.Size.Height * 2));

            IBarcodeReader reader = new BarcodeReader();
            reader.Options.CharacterSet = "UTF-8";
            Result result = reader.Decode(img);
            if (result != null)
            {
                //输出源码
                richTextBox1.AppendText(result.Text);
                richTextBox1.AppendText("\n");
                //输出追溯码
                string qrCode = result.Text;
                if (qrCode.Length == 38)
                {
                    qrCode = qrCode.Substring(16, 16);
                }
                if (qrCode.Length == 46)
                {
                    qrCode = qrCode.Substring(16, 24);
                }
                richTextBox1.AppendText(qrCode);
            }
            else
            {
                richTextBox1.AppendText("请选择正确的二维码图片");
            }




            richTextBox1.AppendText("\n");

            this.WindowState = FormWindowState.Normal;
        }

        #endregion


        #region 二维码识别模块

        /// <summary>
        /// 选择文件路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_show_filepath_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog(this.Owner) == DialogResult.OK)
            {
                tb_file_path.Text = folderBrowserDialog1.SelectedPath;
            }
        }



        private void tb_tmsb_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(tb_file_path.Text))
            {

                foreach (string filePath in Directory.EnumerateFiles(tb_file_path.Text))
                {

                    if (Path.GetExtension(filePath) == ".png" || Path.GetExtension(filePath) == ".jpg")
                    {
                        BarcodeReader reader = new BarcodeReader();     //初始化ZXING插件
                        reader.Options.CharacterSet = "UTF-8";          //设置二维码编码
                        Bitmap img = new Bitmap(filePath);
                        try
                        {
                            Result result = reader.Decode(img);     //读取二维码
                            if (result != null)
                            {
                                string txt_code = result.Text;
                                if (cb_sfgsh.Checked)   //判断是否格式化，去掉前后防伪码
                                {
                                    txt_code = txt_code.Substring(16, 24);
                                }
                                rt_tmsb.AppendText(txt_code);
                            }
                            else
                            {
                                rt_tmsb.AppendText(filePath + "解析失败！");
                            }

                            rt_tmsb.AppendText("\n");
                        }
                        catch
                        {
                            rt_tmsb.AppendText(filePath + "解析失败！");
                            rt_tmsb.AppendText("\n");
                        }

                        img.Dispose();  //释放图片资源
                    }
                    else
                    {
                        rt_tmsb.AppendText(filePath + "不是png或jpg格式的图片");
                        rt_tmsb.AppendText("\n");
                    }


                }

            }
            else
            {
                rt_tmsb.AppendText("请选择正确的二维码文件夹路径");
                rt_tmsb.AppendText("\n");

            }

        }




        #endregion


        #region 二维码生成模块


        private void bt_show_filepath2_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog(this.Owner) == DialogResult.OK)
            {
                tb_file_path2.Text = folderBrowserDialog1.SelectedPath;
            }
        }


        private void tb_tmsc_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(tb_file_path2.Text))
            {
                if (rt_tmsc.Text.Trim().Length > 0)
                {
                    // 分割录入的二维码字符串
                    var qrs = rt_tmsc.Text.Trim().Split('\n');
                    int imgNo = 1;
                    int i = 0;

                    //创建PDF文件

                    //iTextSharp.text.Document document = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(5 * 125, qrs.Count() / 5 * 125));
                    iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 2, 2, 10, 10);
                    PdfWriter Writer = PdfWriter.GetInstance(document, new FileStream(tb_file_path2.Text.Trim() + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf", FileMode.Create));
                    document.Open();
                    document.Add(new iTextSharp.text.Paragraph("测试测试测试测试测试测试测试测试测试"));


                    foreach (var item in qrs)
                    {
                        BarcodeWriter writer = new BarcodeWriter();
                        writer.Format = BarcodeFormat.QR_CODE;
                        QrCodeEncodingOptions options = new QrCodeEncodingOptions
                        {
                            DisableECI = true,//设置内容编码
                            CharacterSet = "UTF-8",  //设置二维码的宽度和高度
                            Width = 100,
                            Height = 100,
                            Margin = 1//设置二维码的边距,单位不是固定像素
                        };

                        writer.Options = options;
                        Bitmap map = writer.Write(item.Trim());
                        string imgpath = tb_file_path2.Text.Trim() + "\\" + imgNo + ".png";
                        map.Save(imgpath);


                        iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgpath);
                        // 图片位置
                        var x = i % 5 * 120;
                        var y = i / 5 * 120;
                        Console.WriteLine(x + "-----" + y);
                        if (y > document.PageSize.Height)
                        {
                            document.NewPage();
                            i = 0;
                            x = i % 5 * 120;
                            y = i / 5 * 120;
                        }
                        img.SetAbsolutePosition(x, y);

                        document.Add(img);


                        i++;
                        imgNo++;

                    }


                    document.Close();
                    Writer.Close();
                }


            }
            else
            {
                rt_tmsc.AppendText("请选择正确的二维码文件夹路径");
                rt_tmsc.AppendText("\n");

            }

        }



        #endregion

        #endregion

        #region 注册热键 ctrl+alt+Q


        [FlagsAttribute]
        public enum KeyModifiers
        {
            None = 0,
            Alt = 1,
            Ctrl = 2,
            Shift = 4,
            WindowsKey = 8
        }


        private void Main_Load(object sender, EventArgs e)
        {
            uint ctrlHotKey = (uint)(KeyModifiers.Alt | KeyModifiers.Ctrl);
            // 注册热键为Alt+Ctrl+C, "100"为唯一标识热键
            RegisterHotKey(Handle, 100, ctrlHotKey, Keys.Q);
        }
        //热键按下执行的方法
        private void GlobalKeyProcess()
        {
            this.WindowState = FormWindowState.Minimized;
            //窗口最小化需要一定的时间 使用线程
            Thread.Sleep(200);
            bt_imagecut.PerformClick();
        }

        protected override void WndProc(ref Message m)
        {
            //如果m.Msg的值为0x0312那么表示用户按下了热键
            const int WM_HOTKEY = 0x0312;
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    if (m.WParam.ToString() == "100")
                    {
                        GlobalKeyProcess();
                    }
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 卸载热键
            UnregisterHotKey(Handle, 100);
        }
        #endregion

    }
}
